<template>
  <div class="login">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>青少年心理健康预警系统</span>
        <div class="role-select-container">
          <!-- 登录角色下拉框 -->
          <el-dropdown @command="handleRoleSelect">
            <span class="el-dropdown-link">
              登录角色：{{ selectedRole || "请选择" }}
              <i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="student">学生</el-dropdown-item>
              <el-dropdown-item command="parent">家长</el-dropdown-item>
              <el-dropdown-item command="admin">管理员</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>

          <!-- 当前选择 -->
          <p v-if="selectedRole" class="selected-role-info">
            已选择：
            {{
              selectedRole === "student"
                ? "学生"
                : selectedRole === "parent"
                ? "家长"
                : "管理员"
            }}
          </p>
        </div>

        <el-form :model="form" ref="form" :rules="rules">
          <el-form-item label="用户名" prop="userName">
            <el-input type="text" v-model="form.userName"></el-input>
          </el-form-item>

          <el-form-item label="密码" prop="passWord">
            <el-input
              type="password"
              v-model="form.passWord"
              :show-password="true"
            ></el-input>
          </el-form-item>

          <el-form-item>
            <div class="button-group">
              <el-button
                type="primary"
                :loading="loading"
                @click="login('form')"
                >登录</el-button
              >
              <el-button
                type="primary"
                @click="
                  $router.push({
                    path: '/register',
                    query: { role: selectedRole },
                  })
                "
              >
                去注册
              </el-button>
            </div>
          </el-form-item>
        </el-form>
      </div>
    </el-card>
  </div>
</template>

<script>
import { nameRule, passRule } from "@/utils/validate";
import { loginApi } from "@/api/auth";

export default {
  name: "LoginPage",
  data() {
    return {
      selectedRole: "",
      form: {
        userName: "",
        passWord: "",
      },
      rules: {
        userName: [{ validator: nameRule, trigger: "blur" }],
        passWord: [{ validator: passRule, trigger: "blur" }],
      },
      loading: false,
    };
  },
  methods: {
    handleRoleSelect(role) {
      this.selectedRole = role;
      console.log("选择了角色：", role);
    },

    async login(formRef) {
      this.$refs[formRef].validate(async (valid) => {
        if (!valid) return;
        if (!this.selectedRole) {
          this.$message.warning("请选择登录角色（学生/家长/管理员）");
          return;
        }

        const payload = {
          id: 0,
          userName: this.form.userName,
          passWord: this.form.passWord,
          role: this.selectedRole,
        };

        try {
          this.loading = true;
          const res = await loginApi(payload);

          if (res && res.code === 200) {
            const { token, userName, role, userId } = res.data;
            if (!token) {
              this.$message.error("后端未返回 token,请检查接口");
              return;
            }

            // 🔑 保存到 localStorage
            localStorage.setItem("token", token);
            localStorage.setItem(
              "userInfo",
              JSON.stringify({ userName, role, userId })
            );

            this.$message.success("登录成功");
             if (role === 'student') {
              this.$router.push("/student/home/info");
            } else if (role === 'parent') {
              this.$router.push("/parent"); // 根据实际路由调整
            } else if (role === 'admin') {
              this.$router.push("/admin"); // 根据实际路由调整
            } else {
              this.$router.push("/"); // 默认跳转
            }
           
          } else {
            this.$message.error(res?.message || "登录失败");
          }
        } catch (error) {
          console.error("登录异常", error);
          this.$message.error("服务器异常，请稍后重试");
        } finally {
          this.loading = false;
        }
      });
    },
  },
};
</script>


<style lang="scss">
.login {
  width: 100%;
  height: 100vh; // 使用视口高度，确保容器占满整个屏幕高度
  position: absolute;
  top: 0; // 定位到页面顶部
  left: 0; // 定位到页面左侧
  background: url("@/assets/yier.jpg");
  background-size: cover; // 让背景图覆盖整个容器
  background-position: center;
  background-color: rgba(220, 239, 244, 0.03);
  background-blend-mode: overlay;
  filter: brightness(1.1);
  background-repeat: no-repeat; // 防止背景图重复
  background-attachment: fixed; // 固定背景图，滚动时不跟随移动
}

.box-card {
  width: 700px;
  margin: 200px auto;
  // 进一步降低卡片背景透明度，减少对背景图的遮挡
  background-color: rgba(255, 255, 255, 0.15);
  backdrop-filter: none;
  border: 1px solid rgba(244, 241, 241, 0.2); // 浅边框勾勒卡片轮廓
}

.el-card__header {
  font-size: 50px;
  background-color: transparent;
  color: #222; // 标题文字颜色加深
}
// 调整表单标签文字样式
.el-form-item__label {
  font-size: 16px;
  color: #333;
}
.el-button {
  width: 100%;
}
// 调整输入框文字样式
// 调整输入框文字样式
.el-input__inner {
  font-size: 16px;
  color: #222; // 文字颜色加深，增强与背景对比度
  background-color: rgba(255, 255, 255, 0.4); // 降低输入框背景透明度，减少亮度
  border: 2px solid #bbb; // 边框颜色加深，更清晰
}

// 调整下拉选择相关文字样式
.el-dropdown-link,
.selected-role-info {
  font-size: 16px;
  color: #333;
}

.button-group {
  display: flex;
  gap: 10px;
  justify-content: center;
}

.button-group .el-button {
  flex: 1;
  min-width: 120px;
}
</style>